$(document).ready(function(){
	new HttpUtils().get('com.lvtu.dashboard.api.all', null, function(httpResult) {
		var code = httpResult.code;
		if("1" != code) {
			alert(httpResult.message);
			return;
		}
		var data = httpResult.data;
		if(!data) {
			console.log("请求结果为空");
			return;
		}
		var list = data.list;
		if(!list) {
			console.log("请求结果为空");
			return;
		}
		var methodTags = new Array(list.length);
		for(var i = 0; i<list.length; i++) {
			methodTags[i] = list[i].api;
		}
		/**方法自动补全搜索*/
	    $("#method").autocomplete({
	    	source: methodTags
	    });
	});
	// 标识当前已有行数
	var currentStartIndex = 0;
	
	var logHtmlDataResult = "";
	
	$("#searchLog").click(function(){
		$('#page_values').html("");
		var param = getRequestParam();
		var startTime = param.startTime;
		var endTime = param.endTime;
		var validateResult = validate(startTime, endTime);
		if(!validateResult) {
			alert('日期格式不正确，或者结束时间在起始时间之前');
			return;
		}
		new HttpUtils().post("com.lvtu.dashboard.search.log", null, function(data){
			currentStartIndex = 0;
			logHtmlDataResult = "";
			$("#datacontent").empty();
			renderLogSearchList(data);
		});
	});
	
	function validate(startTime, endTime) {
		var reg = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/;
		if(startTime || startTime.trim() != '') {
			if(!reg.test(startTime)) {
				return false;
			}
		}
		if(endTime || endTime.trim() != '') {
			if(!reg.test(endTime)) {
				return false;
			}
		}
		var startTimeDate = getDate(startTime);
		var endTimeDate = getDate(endTime);
		if(endTime == null || endTimeDate == null) {
			return true;
		}
		if(startTimeDate > endTimeDate) {
			return false;
		}
		return true;
	}
	
	function getDate(dateStr) {
		var reg = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/;
		if(!reg.test(dateStr)) {
			return null;
		}
		dateStr = dateStr.replace(/-/g,'/');
		return new Date(dateStr);
	}
	
	function renderLogSearchList(data) {
		// 多个请求的日志列表
		var logData = data.data;
		var logRowsList = logData.logs;
		var result = "";
		if(logRowsList) {
			// 遍历每一个请求中的日志信息
			$.each(logRowsList, function eachRowsList (index, logObject) {
				if(logObject == null) {
					return;
				}
				var rowResult = generateTableRow(index, logObject);
				result = result + rowResult;
			});
			$("#datacontent").append(result);
			$.each(logRowsList, function renderTimeList (index, logObject) {
				if(logObject == null) {
					return;
				}
				var currentIndex = currentStartIndex + index;
				var param = getTimeList(logObject);
				$('#log_time_detail_' + currentIndex).highcharts(param);
			    $('#log_time_detail_' + currentIndex).css({display:'none', visibility:'hidden'});
			    $('#total_time_li_' + currentIndex).click(function() {
			        var disvalue = $("#log_time_detail_" + currentIndex).css("display");
			        if('none' == disvalue) {
			            $('#log_time_detail_' + currentIndex).css({display:'block', visibility:'visible'});
			        } else {
			            $('#log_time_detail_' + currentIndex).css({display:'none', visibility:'hidden'});
			        }
			    });
			    
			    $('#log_json_detail_' + currentIndex).JSONView(logObject);
			    $('#log_json_detail_' + currentIndex).JSONView('expand');
			    $("#log_json_detail_" + currentIndex).hide();
			    $('#log_json_li_' + currentIndex).click(function() {
			    	$("#log_json_detail_" + currentIndex).slideToggle();
			    });
			    
			    var slideHeight = 75; // px  
			    var defHeight = $('#log_detail_content_wrap_' + currentIndex).height();
			    if (defHeight >= slideHeight) {
			    	$('#log_detail_content_wrap_' + currentIndex).css('height', slideHeight + 'px');
			    	$('#read-more_' + currentIndex).append('<a href="#">更多</a>');
			    	$('#read-more_'+ currentIndex + ' a').click(function() {
			    		var curHeight = $('#log_detail_content_wrap_' + currentIndex).height();
			    		if (curHeight == slideHeight) {
			    			$('#log_detail_content_wrap_' + currentIndex).animate({height : defHeight}, "normal");
			    			$('#read-more_' + currentIndex + ' a').html('收起');
			    			$('#gradient_' + currentIndex).fadeOut();
			    		} else {
			    			$('#log_detail_content_wrap_' + currentIndex).animate({height : slideHeight}, "normal");
			    			$('#read-more_'+ currentIndex + ' a').html('更多');
			    			$('#gradient_' + currentIndex).fadeIn();
			    		}
			    		return false;
			    	});
			    }  
			});
			currentStartIndex = currentStartIndex + logRowsList.length;
			logHtmlDataResult = logHtmlDataResult + result;
		}
		
		var page = logData.page;
		if(page.page < page.totalPage) {
			$("#page_total_page").html(page.page + '/' + page.totalPage + '页');
			$("#total_size").html(page.totalSize + '条');
			$("#pagebanel").css({display:'block', visibility:'visible'});
		} else {
			$("#pagebanel").css({display:'none', visibility:'hidden'});
		}
		$('#page_values').html(page.page + "," + page.pageSize + "," + page.totalPage);
		return result;
	}

	function generateTableRow(index, logObj) {
		var firstChannel = logObj.firstChannel;
		var secondChannel = logObj.secondChannel;
		var method = logObj.method;
		var version = logObj.version;
		var requestTime	= logObj.requestTime;
		var responseTime = logObj.responseTime;
		var logList = logObj.logDetail;
		var requestTimeDetail = logObj.requestTimeDetail;

		var currentIndex = currentStartIndex + index;
		var result = '';
		result = result + '<div class="loginforow"><ul class="logfinforow_ul"><li class="first_channel_li">' + firstChannel + '</li>'
				+ '<li class="second_channel_li">' + secondChannel + '</li>'
				+ '<li class="method_li">' + method + '</li>' 
				+ '<li class="version_li">' + version + '</li>'
				+ '<li class="log_json_li" id="log_json_li_' + currentIndex + '">JSON</li>'
				+ '<li class="total_time_li" value="100" id="total_time_li_' + currentIndex + '">' + (responseTime - requestTime) + 'ms</li>'
				+ '</ul>' 
				+ '<div id="log_time_detail_' + currentIndex + '"></div>'
				+ '<div class="log_json_detail" id="log_json_detail_' + currentIndex + '"></div>'
				+ '<div class="log_detail_content_wrap" id="log_detail_content_wrap_' + currentIndex + '"><div class="log_detail_content">';
		$.each(logList, function eachLogs(j, log) {
			result = result + log + '<br/>';
		});
		result = result + '</div>'
			+ '<div id="gradient_' + currentIndex + '"></div>'
			+ '</div>'
			+ '</div>'
			+ '<div class="read-more" id="read-more_' + currentIndex + '"></div>';
		return result;
	}
	
	function getTimeList(logObj) {
		var requestTimeDetails = logObj.requestTimeDetail;
		if(!requestTimeDetails) {
			return null;
		}
		var requestTime	= logObj.requestTime;
		var responseTime = logObj.responseTime;
		var categories = new Array(requestTimeDetails.length < 12 ? 12 : requestTimeDetails.length);
		var seriesData = new Array(requestTimeDetails.length < 12 ? 12 : requestTimeDetails.length);
		var i = 1;
		$.each(requestTimeDetails, function(index, timeDetail) {
			var timeType = timeDetail.timeType;
			var requestName = timeDetail.requestName;
			var tempRequestTime	= timeDetail.requestTime;
			var millisecond = timeDetail.millisecond;
			if('ALL' == timeType) {
				categories[0] = requestName;
				var tempData = [0, millisecond];
				seriesData[0] = tempData;
			} else {
				categories[index] = requestName;
				var tempData = [tempRequestTime - requestTime, tempRequestTime - requestTime + millisecond];
				seriesData[index] = tempData;
				index++;
			}
		});
		if(categories[0]) {
			for(var i = 1; i<categories.length; i++) {
				if(categories[i]) {
					continue;
				}
				categories[i] = '';
				seriesData[i] = [0, 0];
			}
		}
		var param = {
	        chart: {
	            type: 'columnrange',
	            inverted: true
	        },
	        title: {
	            text: '接口耗时详情'
	        },
	        // subtitle: {
	        //     text: 'Observed in Vik i Sogn, Norway, 2009'
	        // },
	        xAxis: {
	            categories: categories
	        },
	        yAxis: {
	            title: {
	                text: '单接口耗时(ms)'
	            }
	        },
	        tooltip: {
	            valueSuffix: 'ms'
	        },
	        plotOptions: {
	            columnrange: {
	                dataLabels: {
	                    enabled: true,
	                    formatter: function() {
	                        return this.y + 'ms';
	                    }
	                }
	            }
	        },
	        legend: {
	            enabled: false
	        },
	        series: [{
	            name: '单接口耗时',
	            data: seriesData
	        }]
		};
		return param;
	}
	
	// 开始时间选择器
	$( "#startTime" ).datetimepicker({
        timeFormat: "HH:mm:ss",
        dateFormat: "yy-mm-dd",
        showOtherMonths: true,
      	selectOtherMonths: true,
      	changeMonth: true,
      	changeYear: true,
      	showButtonPanel: true
    });

	// 结束时间选择器
	$( "#endTime" ).datetimepicker({
        timeFormat: "HH:mm:ss",
        dateFormat: "yy-mm-dd",
        showOtherMonths: true,
      	selectOtherMonths: true,
      	changeMonth: true,
      	changeYear: true,
      	showButtonPanel: true
    });

    var versionTags = ["1.0.0", "2.0.0", "3.0.0", "4.0.0", "5.0.0", "6.0.0", "7.0.0", "8.0.0", "9.0.0", "10.0.0"];
    $("#version").autocomplete({
    	source: versionTags
    });

    var firstChannelTags = ["Android", "IPhone", "TOUCH", "WIN8", "WIN10"];
    $("#firstChannel").autocomplete({
    	source: firstChannelTags
    });
    
    var extendKeywordCount = 0;
    $('#keyword_plus').click(function() {
    	var contactResult = '<div class="inputrow" id="inputrow_' + extendKeywordCount 
    					+ '"><label class="keywordlabel">关键字</label><input type="text" class="keyword" id="keyword_' 
    					+ extendKeywordCount + '"><span class="keyword_option keyword_minus" id="keyword_minus_' + extendKeywordCount + '"></span></div>';
    	$('#extend_keyword_content').append(contactResult);
    	$('#keyword_minus_' + extendKeywordCount).click(function() {
        	var temp = $(this).parent();
    		temp.remove();
    	});
    	extendKeywordCount++;
	});
    
    $("#pagebanel").click(function() {
		var param = getRequestParam();
		var startTime = param.startTime;
		var endTime = param.endTime;
		var validateResult = validate(startTime, endTime);
		if(!validateResult) {
			alert('日期格式不正确，或者结束时间在起始时间之前');
			return;
		}
		new HttpUtils().post("com.lvtu.dashboard.search.log", null, function(data){
			renderLogSearchList(data);
		});
    });
    
    
    function getRequestParam() {
    	var pageInfoStr = $('#page_values').html();
    	var pageInfo = pageInfoStr.split(",");
    	//page.page + "," + page.pageSize + "," + page.totalPage
    	var page = pageInfo[0];
    	if(!page) {
    		page = '0';
    	}
    	var pageSize = pageInfo[1];
    	if(!pageSize) {
    		pageSize = '20';
    	}
    	var totalPage = pageInfo[2];
    	if(!totalPage) {
    		totalPage = '1';
    	}
    	if(parseInt(totalPage) <= parseInt(page)) {
    		return;
    	}
    	var startTime = $("#startTime").prop('value');
		var endTime = $("#endTime").prop('value');
		var lvversion = $("#lvversion").prop('value');
		var method = $("#method").prop('value');
		var version = $("#version").prop('value');
		var threadName = $("#threadName").prop('value');
		var firstChannel = $("#firstChannel").prop('value');
		var secondChannel = $("#secondChannel").prop('value');
		var ip = $("#ip").prop('value');
		var latitude = $("#latitude").prop('value');
		var longitude = $("#longitude").prop('value');
		var lvsessionid = $("#lvsessionid").prop('value');
		var keyword = $("#keyword").prop('value');
		var keywords = new Array(extendKeywordCount + 1);
		keywords[0] = keyword;
		for(var i = 0; i <= extendKeywordCount; i++) {
			var temp = $('#keyword_' + i);
			if(temp) {
				keywords[i+1] = temp.prop('value');
			}
		}
		var param = {
				startTime:startTime,
				endTime:endTime,
				lvversion:lvversion,
				method:method,
				version:version,
				threadName:threadName,
				firstChannel:firstChannel,
				secondChannel:secondChannel,
				ip:ip,
				latitude:latitude,
				longitude:longitude,
				lvsessionid:lvsessionid,
				keyword:keywords,
				page:parseInt(page)+1,
				pageRows:pageSize
		};
		
		return param;
    }
    
    
    var json = {
    		"threadName":"FLUME-c9e643e9-c253-4baf-8028-33ed1cab3424",
    		"lvsessionid":"",
    		"userId":"",
    		"ip":"172.17.42.1",
    		"lvversion":"",
    		"longitude":"",
    		"latitude":"",
    		"firstChannel":"",
    		"secondChannel":"",
    		"udid":"",
    		"osVersion":"",
    		"method":"",
    		"version":"",
    		"requestTime":1470367483786,
    		"responseTime":1470367484142,
    		"param1":null,
    		"param2":null,
    		"param3":null,
    		"param4":null,
    		"param5":null,
    		"param6":null,
    		"param7":null,
    		"param8":null,
    		"param9":null,
    		"param10":null,
    		"logDetail":[
    		             "2016-08-05 11:24:43,786 INFO[LvLogS]client-service [FLUME-c9e643e9-c253-4baf-8028-33ed1cab3424] (BaseAccessFilter.java:40) - in BaseAccessFilter.....", 
    		             "2016-08-05 11:24:44,138 INFO[LvLogS]client-service [FLUME-c9e643e9-c253-4baf-8028-33ed1cab3424] (ApiMethodIntercept.java:179) - after invoke Object:com.lvtu.service.api.rop.service.ship.ClientShipOrderServiceImpl@21ac1283,Method:countPrice", 
    		             "2016-08-05 11:24:44,142 WARN[LvLogS]client-service [FLUME-c9e643e9-c253-4baf-8028-33ed1cab3424] (FlumeAdapterLogFilter.java:50) - FLUME-LOG-END"
    		             ],
    		"requestTimeDetail":[
    		                     {
    		                    	 "timeType":"ALL",
    		                    	 "requestName":"",
    		                    	 "requestVersion":"",
    		                    	 "requestTime":1470367483786,
    		                    	 "responseTime":1470367484142,
    		                    	 "millisecond":356}, 
    		                     {
    		                    	 "timeType":"DUBBO",
    		                    	 "requestName":"com.lvmama.comm.pet.service.user.UserUserProxy",
    		                    	 "requestVersion":"getUserUserByPk",
    		                    	 "requestTime":1470367483794,
    		                    	 "responseTime":1470367483801,
    		                    	 "millisecond":7}, 
    		                    ]
    };
    $("#log_json_detail_0").JSONView(json);
    $('#log_json_detail_0').JSONView('expand');
    
//    
    
    
    
    
})
